package com.example.brain2;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.GridView;
import android.widget.ImageView;

public class ActualGameActivity extends Activity {

	public static int getGAME_SIZE() {
		return GAME_SIZE;
	}

	private static final int HARD_GAME = 20;
	private static final int MEDIUM_GAME = 16;
	private static final int EASY_GAME = 12;
	private static int GAME_SIZE;

	protected static final String TAG = "MainActivity";
	private ImageAdapter adapter;
	private static final int PAIRS_FOR_WIN = GAME_SIZE / 2;
	private Integer clickedPosition;
	private Image clickedType;
	private int matchedPairs;
	private String subfolder;

	// private Integer[] pictureIds;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_actual_game);
		String[] listOfImages = null;

		// set the folder of images
		int[] gameType = getIntent().getIntArrayExtra("ImageTypes");
		if (gameType[0] == 1) {
			subfolder = "animals";
			Log.i(TAG, "animals");
		} else if (gameType[0] == 2) {
			subfolder = "weapons";
			Log.i(TAG, "weapons");
		} else if (gameType[0] == 2) {
			subfolder = "objects";
			Log.i(TAG, "objects");
		}
		// set difficulty
		if (gameType[1] == 1)
			GAME_SIZE = EASY_GAME;
		else if (gameType[1] == 2)
			GAME_SIZE = MEDIUM_GAME;
		else if (gameType[1] == 3)
			GAME_SIZE = HARD_GAME;

		try {
			listOfImages = getFilesFromFolderRandomly(subfolder);
		} catch (IOException e) {
			Log.i("ERROR", "Error getting the images from folder");
		}
		startGame(listOfImages); // start
	}

	// start the actual card game
	private void startGame(String[] listOfImages) {

		InputStream inStream = null; // initialize
		ImageView frontImageView = (ImageView)findViewById(R.id.front_image);; // initialize
		ImageView backImageView = (ImageView)findViewById(R.id.back_image);
		matchedPairs = 0;
		List<Cell> matrix = new ArrayList<Cell>(); // initialize the List of
													// Cells
		final String[] list = listOfImages; // make a copy
		// add new Cells to Matrix
		clearState();
		for (int y = 0; y < GAME_SIZE; y++) {
			matrix.add(new Cell());
		}

		// make a stream, for every file in the user chosen folder, and create
		// an imageView from it
		for (int i = 0; i < GAME_SIZE/2; i++) {
			try {
				inStream = this.getAssets().open(list[i]);
				frontImageView.setImageBitmap(BitmapFactory.decodeStream(inStream));
				// we need to set in each cell's Image its field backPicture
				// using the ImageView from the inputStream above
				matrix.get(i).setCard(new Image(frontImageView,backImageView));
				
			} catch (IOException e) {
				Log.i("ERROR INSTREAM", "Can't read the inputStream");
			} finally {
				try {
					inStream.close();
				} catch (IOException e) {
					Log.i("ERROR CLOSING INSTREAM",
							"Error while closing inputStream");
					e.printStackTrace();
				}
			}
		}
		Collections.shuffle(matrix);// shuffle the cells (and images respectively) randomly
		
		adapter = new ImageAdapter(this, matrix, new OnImageClickedListener() {

			@Override
			public void onImageClicked(Image image, int position) {
				if (hasMatch(image, position)) {
					matchedPairs++;
					if (matchedPairs == PAIRS_FOR_WIN) { // win condition
						Intent intentBackToMain = new Intent(
								ActualGameActivity.this, MainActivity.class);
						startActivity(intentBackToMain);
					}
				} else {
				}
			}
		});
		GridView grid = (GridView) findViewById(R.id.gameGridView);
		grid.setAdapter(adapter);
	}

	// marks all the necessary images and puts them in a string array, and shuffles them
	private String[] getFilesFromFolderRandomly(String dirFrom) throws IOException {
		Resources res = getResources(); // if you are in an activity
		AssetManager am = res.getAssets();
		String fileList[] = am.list(dirFrom);
		fileList = shuffleArray(fileList);
		return fileList;
	}

	// this method checks whether the 2 clicked images are the same, if true,
	// updates the found pairs and locks them
	private boolean hasMatch(Image image, int position) {
		boolean result = false;
		if (clickedPosition == null) {
			clickedPosition = position;
			clickedType = image;
		} else {
			if (clickedPosition == position) {
				clearState();
			} else {
				if (clickedType.equals(image)) {
					adapter.lockCard(position);
					adapter.lockCard(clickedPosition);
					clearState();
					matchedPairs++;
					return true;
				} else {
					adapter.closeCards(position);
					adapter.closeCards(clickedPosition);
					clearState();
				}
			}
		}
		return result;
	}

	private void clearState() {
		clickedPosition = null;
		clickedType = null;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.actual_game, menu);
		return true;
	}
	
	//shuffles the strings in the array randomly
	private static String [] shuffleArray(String[] array) {
		Random random = new Random();
		for (int i = array.length - 1; i > 0; i--) {
			int index = random.nextInt(i + 1);			
			String temp = array[index];
			array[index] = array[i];
			array[i] = temp;
		}
		return array;
	}

}
